import { ReactNode, useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import type { RouterData } from '@/api/menu/getRouters'

import type { RouterInfoMeta }  from '@/store/modules/currentPage'
import useCurrentPage from '@/store/modules/currentPage'
import useHistoryTags from '@/store/modules/historyTags'
import useAuth from '@/hooks/usePageAuth';
import { cloneDeep } from 'lodash';

type Props = {
  element: ReactNode,
  routerMeta: RouterData,
  path: string,
  stack: RouterInfoMeta[]
}

const RenderPage: React.FC<Props> = ({ element, routerMeta, path, stack }) => {
  const historyTags = useHistoryTags()
  const [loading, setLoading] = useState(false)

  const navigate = useNavigate();
  const { isAuthenticated, handleUnauthorized } = useAuth();
  const currentPage = useCurrentPage();

  useEffect(() => {
    // history-tags
    const search = window.location.search
    const item = {key: routerMeta.name, path: `${path}${search}`, name: routerMeta.meta.title}
    historyTags.routerPushTags(item)
    // breadcrumb
    const stackData = cloneDeep(stack)
    const last = stackData[stackData.length - 1]
    last.href = undefined
    if (stackData.length > 1) {
      stackData.unshift({title: '首页', 'href': '/'})
    }
    currentPage.changeRoute(routerMeta.meta, stackData, routerMeta.name)
    setLoading(true)
  }, []);

  if(!loading) return null
  return element;
}

export default RenderPage